<template>
  <div>
    <Page auto-content-height>
      <div class="bg-card mb-4 rounded-lg px-4 pt-6">
        <BaseForm />
      </div>
      <!-- 表格 -->
      <FosoTable
        :tool-bar-button-text="$t('sys.apis.addApi')"
        table-title="API管理"
        table-titlehelp="API管理帮助"
        @add="openDrawerHandle('add', $event)"
      >
        <!-- 操作列 -->
        <template #action="{ row }">
          <OperationColumn
            :row="row"
            @delete="DeleteHandle(row)"
            @edit="openDrawerHandle('edit', $event)"
          />
        </template>
      </FosoTable>
    </Page>
    <!-- 弹窗框 -->
    <Drawer class="w-[40%]" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { ElTag } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { deleteApi, getApiList } from '#/api/sys/api';
import { OperationColumn } from '#/components/FosoTablePro/index';
import { useFosoTable } from '#/components/FosoTablePro/use-foso-config';
import { useFosoTableConfig } from '#/components/FosoTablePro/use-foso-table';

import ExtraDrawer from './components/drawer.vue';
// 定义表单
const [BaseForm] = useVbenForm({
  // 默认展开
  collapsed: true,
  layout: 'horizontal',
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询按钮',
  },
  handleSubmit: searchHandle,
  wrapperClass: 'grid-cols-1 md:grid-cols-3',
  schema: [
    {
      component: 'Input',
      fieldName: 'path',
      label: $t('sys.apis.path'),
    },
    {
      component: 'Input',
      fieldName: 'serviceName',
      label: $t('sys.apis.serviceName'),
    },
    {
      component: 'Input',
      fieldName: 'group',
      label: $t('sys.apis.group'),
    },
    {
      component: 'Input',
      fieldName: 'description',
      label: $t('sys.apis.description'),
    },
  ],
});
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});

// 使用 useFosoTable hook 生成配置
const { gridOptions } = useFosoTableConfig({
  columns: [
    {
      type: 'checkbox',
      width: 50,
    },

    {
      title: $t('sys.apis.path'),
      field: 'path',
    },
    {
      title: $t('sys.apis.group'),
      field: 'group',
    },
    {
      title: $t('sys.apis.serviceName'),
      field: 'serviceName',
    },
    {
      title: $t('sys.apis.description'),
      field: 'description',
      formatter: ({ cellValue }: any) => $t(`sys.${cellValue}`), // 国际化
    },
    {
      title: $t('sys.apis.method'),
      field: 'method',
    },
    // 状态
    {
      title: $t('sys.apis.must'),
      field: 'status',
      slots: {
        default: ({ row }: any) => {
          return (
            <ElTag type={row.isRequired ? 'success' : 'info'}>
              {row.isRequired ? $t('sys.menu.on') : $t('sys.menu.off')}
            </ElTag>
          );
        },
      },
    },
    // 创建时间
    {
      title: $t('sys.menu.createTime'),
      field: 'createTime',
      minWidth: 120,
      formatter: ['formatDate', 'yyyy-MM-dd'],
    },
    {
      title: $t('sys.menu.operation'),
      width: 200,
      slots: { default: 'action' },
    },
  ],

  requestApi: getApiList,
});

const { FosoTable, FosoTableApi } = useFosoTable(gridOptions);

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {any} row - 要编辑的行数据对象，包含字典相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: any): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.apis.editApi') });
    drawerApi.setData({ type: 'editData', id: row.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.apis.addApi') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 删除字典
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: any): Promise<void> {
  try {
    await deleteApi(row.id);
    ElMessage.success('删除成功');
    FosoTableApi.commitProxy('reload');
  } catch {
    ElMessage.error('删除失败');
  }
}

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  FosoTableApi.commitProxy('reload');
  drawerApi.close();
};

/**
 * @author Buke
 * @description 搜索职位
 * @returns {void}
 * @todo 职位查询问题
 */
function searchHandle(values: Record<string, any>): void {
  FosoTableApi.commitProxy('query', values);
}
</script>
